var jifen = require('../util/updateJiFeng');


var express = require('express');
var router = express.Router();
var db = require('../sql')
// 1.获取所有商店的信息
router.get('/oftenShopMapData', async function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // 获取用户id
  const id = req.query.userid;
  // 用户id查询用户的订单
  const useridList = await new Promise((resolve, reject) => {
    db.query('select * from userorder where userid=?', id, function (err, data) {
      resolve(data)
    })
  })
  const userShopIds = Array.from(new Set(useridList.map(n => n.shopid)));
  // console.log(userShopIds);
  // const RES = [];
  // for (let shopid of userShopIds) {
  //   await new Promise((resolve,reject)=>{
  //     db.query('select * from shop where id=?',shopid, function (err, data) {
  //       RES.push(data[0])
  //       resolve(true);
  //     })
  //   })

  // }
  res.send(userShopIds)
  // db.query('select * from shop', function (err, data) {
  //   res.send(data);
  // })
});

// 1.1获取所有常去的商店的信息
router.get('/shopMapData', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  db.query('select * from shop', function (err, data) {
    res.send(data);
  })
});

// 2.获取指定商店的信息
router.get('/checkedMapData', function (req, res, next) {
  const id = req.query.id;
  db.query('select * from shop where id=?', [id], function (err, data) {
    try {
      res.send(data);
    } catch (err) {
      res.send(err);
    }
  })
});

// 3.根据商店id获取商品列表
router.get('/shopList', function (req, res, next) {
  const { id, openid } = req.query;
  db.query('select * from foodlist where shopid=?', [id], async function (err, data) {
    if (err) {
      throw err
    } else {
      const UserShopCar = new Promise((resolve, reject) => {
        db.query('select * from shopcar where userid=?', openid, function (err, data) {
          if (err) {
            throw err
          } else {
            resolve(data);
          }
        })
      })
      let userShopCarData = await UserShopCar;
      userShopCarData = userShopCarData.map(n => {
        return {
          ...n,
          label: JSON.parse(n.label)
        }
      })
      for (let item of data) {
        item['sumCount'] = userShopCarData.reduce((sum, item2) => {
          if (item2.foodid == item._id) {
            return sum + item2.num;
          } else {
            return sum;
          }
        }, 0)
        item['checkedFood'] = userShopCarData.filter(n => {
          return n.foodid == item._id
        })
        const arr = item.label;
        item.label = [];
        for (let i of arr) {
          await db.query('select * from foodlabel where id=?', [i], function (err, data) {
            if (err) {
              throw err
            } else {
              if (data.length <= 0) return
              item.label.push(...data);
            }
          })
        }
        setTimeout(() => {
          let types = {};
          for (let i of item.label) {
            const tyArr = Object.keys(types);
            if (!tyArr.includes(i.type)) types[i.type] = [];
            types[i.type].push(i);
          }
          item.label = types
        }, 200)
      }
    }
    setTimeout(() => {
      res.send(data);
    }, 300);

  })
});

// 4.添加订单
router.post('/updataOrder', function (req, res, next) {
  const { shopid, foodlist, userid, status, totalprice, total, remarks = '', taketime, createtime } = req.body;
  db.query('INSERT INTO `order` (shopid,foodList,userid,status,totalprice,total,remarks,taketime,createtime) values (?,?,?,?,?,?,?,?,?)',
    [shopid, foodlist, userid, status, totalprice, total, remarks, taketime, createtime],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ msg: '提交成功', code: 200 });
      }
    })
})

// 5.获取用户的所有订单信息
router.get('/userOrder', async function (req, res, next) {
  const id = req.query.userid;
  db.query('select * from `order` where userid=? order by orderid desc', [id], async function (err, data) {
    if (err) {
      throw err
    } else {
      await data.forEach(async (Item, index) => {
        try {
          const foodList = JSON.parse(Item.foodList)
          const newFoodList = []
          await foodList.forEach(async (item) => {
            try {
              const foodlistdata = await new Promise((resolve, reject) => {
                db.query('select * from `foodlist` where shopid=? and _id=?', [item.shopid, item._id],
                  function (err, data) {
                    if (err) {
                      reject(err);
                    } else {
                      resolve(data);
                    }
                  })
              })
              newFoodList.push(foodlistdata);
            } catch (err) {
              throw err
            }
          })
          data[index].foodList = newFoodList
        } catch (err) {
          throw err
        }
      })
      setTimeout(() => {
        res.send({ msg: '查询成功', code: 200, data });
      }, 50)

    }
  })
});

// 6.获取商店的所有订单
router.get('/shopOrder', async function (req, res, next) {
  // const id = req.query.shopid;
  // db.query('select * from userorder where shopid=?', [id], async function (err, data) {
  //   if (err) {
  //     throw err
  //   } else {
  //     await data.forEach(async (Item, index) => {
  //       try {
  //         const foodList = JSON.parse(Item.foodList)
  //         const newFoodList = []
  //         await foodList.forEach(async (item) => {
  //           try {
  //             const foodlistdata = await new Promise((resolve, reject) => {
  //               db.query('select * from `foodlist` where shopid=? and _id=?', [item.shopid, item._id],
  //                 function (err, data) {
  //                   if (err) {
  //                     reject(err);
  //                   } else {
  //                     resolve(data);
  //                   }
  //                 })
  //             })
  //             newFoodList.push(foodlistdata);
  //           } catch (err) {
  //             throw err
  //           }
  //         })
  //         data[index].foodList = newFoodList
  //       } catch (err) {
  //         throw err
  //       }
  //     })
  //     setTimeout(() => {
  //       res.send({ msg: '查询成功', code: 200, data });
  //     }, 50)

  //   }
  // })


  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { shopid } = req.query;
  const OrderRes = await new Promise((resolve, reject) => {
    db.query(`select * from userorder where shopid=?`
      , shopid,
      function (err, data) {
        if (err) {
          reject(err)
        } else {
          resolve({ code: 200, msg: "获取成功", data });
        }
      })
  })
  // 获取订单数据成功
  if (OrderRes.code == 200) {
    for (let n of OrderRes.data) {
      const foodRes = await new Promise((resolve, reject) => {
        db.query(`select * from userorderfoodlist where orderid=?`, [n.orderid],
          function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve({ code: 200, msg: "获取成功", data });
            }
          })
      });
      const food = foodRes.data.map(n => {
        return {
          ...n,
          label: JSON.parse(n.label)
        }
      })
      n.selectShopCar = food
    }
    // 获取所有订单的商品


    res.send({ code: 200, msg: "更新/添加订单成功", data: OrderRes.data })
  }


});

// 7.修改订单状态
router.get('/orderStatusChange', async function (req, res, next) {
  const {orderid:id,status=1} = req.query;
  // 获取
  db.query('update `userorder` set status=? where orderid=?', [status,id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data)
    }
  })
  if(status == 1){
    const foodList = await new Promise((resolve,reject)=>{
      db.query('select * from `userorderfoodlist` where orderid=?', [id], function (err, data) {
        if (err) {
          throw err
        } else {
          // 获取所有符合条件的商品
           resolve(data)
        }
      })
    })
    foodList.forEach(async (n)=>{
      const getSell = await new Promise((resolve,reject)=>{
        db.query('select * from `foodlist` where _id=?', [n._id], function (err, data) {
          if (err) {
            throw err
          } else {
            // 获取所有符合条件的商品
             resolve(data)
          }
        })
      })
      console.log(getSell);
      const newSell = getSell[0].sell+n.num;
      console.log('新数量',newSell);
      await new Promise((resolve,reject)=>{
        db.query('update `foodlist` set sell=? where _id=?', [newSell,n._id], function (err, data) {
          if (err) {
            throw err
          } else {
            resolve(data)
          }
        })
      })
    })
  }
  new Promise((resolve, reject) => {
    db.query('select * from `userorder` where orderid=?', [id], function (err, data) {
      if (err) {
        reject(err)
      } else {
        const obj = {
          userid: data[0].userid,
          totalprice: data[0].sumPrice
        }
        resolve(obj)
      }
    })
  }).then((res) => {
    new Promise((resolve, reject) => {
      const openid = res.userid;
      db.query('select * from user where openid=?', [openid], function (err, data) {
        if (err) {
          reject(err);
        } else {
          if (data.length) {
            resolve({
              userid: res.userid,
              totalprice: res.totalprice,
              nowIntegral: data[0].nowIntegral,
              sumIntegral: data[0].sumIntegral
            })
          } else {
            res.send({ msg: '查询失败', code: 404 })
          }
        }
      })
    }).then(res => {
      let { userid, totalprice, nowIntegral, sumIntegral } = res;
      nowIntegral += totalprice;
      sumIntegral += totalprice;
      db.query('update `user` set nowIntegral=?,sumIntegral=? where openid=?', [nowIntegral, sumIntegral, userid], function (err, data) {
        if (err) {
          throw err
        } else {
          jifen.JiFengRecord({
            msg: "下单成功",
            status: 1,
            Integral: totalprice,
            openid: userid
          });
        }
      })
    })
  })


});

// 8.用户修改订单状态
router.get('/orderStatusChange2', async function (req, res, next) {
  const {orderid:id,status=2,msg} = req.query;
  // 获取
  db.query('update `userorder` set status=?,msg=? where orderid=?', [status,msg,id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data)
    }
  })
  new Promise((resolve, reject) => {
    db.query('select * from `userorder` where orderid=?', [id], function (err, data) {
      if (err) {
        reject(err)
      } else {
        const obj = {
          userid: data[0].userid,
          totalprice: data[0].sumPrice
        }
        resolve(obj)
      }
    })
  }).then((res) => {
    new Promise((resolve, reject) => {
      const openid = res.userid;
      db.query('select * from user where openid=?', [openid], function (err, data) {
        if (err) {
          reject(err);
        } else {
          if (data.length) {
            resolve({
              userid: res.userid,
              totalprice: res.totalprice,
              nowIntegral: data[0].nowIntegral,
              sumIntegral: data[0].sumIntegral
            })
          } else {
            res.send({ msg: '查询失败', code: 404 })
          }
        }
      })
    }).then(res => {
      let { userid, totalprice, nowIntegral, sumIntegral } = res;
      nowIntegral += totalprice;
      sumIntegral += totalprice;
      db.query('update `user` set nowIntegral=?,sumIntegral=? where openid=?', [nowIntegral, sumIntegral, userid], function (err, data) {
        if (err) {
          throw err
        } else {
          jifen.JiFengRecord({
            msg: "下单成功",
            status: 1,
            Integral: totalprice,
            openid: userid
          });
        }
      })
    })
  })


});

// 8.获取商店的所有商品
router.get('/getShopAll', function (req, res) {
  const id = req.query.shopid;
  db.query('select * from foodlist where shopid=?', [id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data)
    }
  })
})

// 9.修改商品状态
router.get('/FoodStatusChange', function (req, res, next) {
  const { id, status } = req.query;
  db.query('update `foodlist` set status=? where _id=?', [status, id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send({
        code: 200,
        data
      })
    }
  })
});

// 10.获取所有商品标签
router.get('/foodlabel', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  db.query('select * from foodlabel', function (err, data) {
    res.send(data);
  })
});

// 11.获取所有商品
router.get('/food', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  db.query('select * from foodlist', function (err, data) {
    res.send(data);
  })
});

// 12.添加商店
router.post('/addShoreData', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let obj = req.body;
  db.query(`insert into shop (name,address,latitude,longitude,phone) 
      values (?,?,?,?,?)`,
    [obj.name, obj.address, obj.latitude, obj.longitude, obj.phone],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send(data);
      }
    })
})

// 13.获取指定商店的完整信息（包括所有商品）
router.get('/ShopAllData', async function (req, res, next) {
  const id = req.query.id;
  let search = req.query.search;
  if (!search) search = ''
  search = `%${search}%`
  db.query('select * from shop where id=?', [id], async function (err, data) {
    if (err) {
      throw err
    } else {
      if (data.length >= 1) {
        const shop = data[0];
        // （1）获取所有商品
        const getShopList = new Promise((resolve, reject) => {
          db.query("select * from foodlist where shopid=? and name like ?", [shop.id, search], function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve(data);
            }
          })
        })
        const shoplist = await getShopList;
        shop['shoplist'] = shoplist
        shoplist.forEach(n => {
          const label = JSON.parse(n.label);
          const labelFull = [];
          label.forEach(async n => {
            const labelItem = await new Promise((resolve, reject) => {
              db.query('select * from foodlabel where id=?', n, function (err, data) {
                if (err) {
                  reject(err);
                } else {
                  resolve(data);
                }
              })
            })
            labelFull.push(labelItem[0]);
          })
          n.label = labelFull;
        })
        // （1）获取所有商品
        const getbindList = new Promise((resolve, reject) => {
          db.query("select * from foodlist where shopid=?", [shop.id], function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve(data);
            }
          })
        })
        const bindList = await getbindList;
        // 收集销售可视化的数据
        const binData = bindList.map(n => {
          return {
            name: n.name,
            value: n.sell
          }
        })

        shop['sellTop'] = binData

        // （2）获取所有订单
        const getorderlist = new Promise((resolve, reject) => {
          db.query('select * from `userorder` where shopid=?', shop.id, function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve(data);
            }
          })
        })
        const orderlist = await getorderlist;
        const fillerOrder = orderlist.filter(n => {
          return n.status == 2
        })
        const changeTimeOrder = fillerOrder.map(n => {
          const date = new Date(Number(n.createtime));
          return {
            totalprice: n.totalprice,
            createtime: `${date.getMonth() + 1}月${date.getDate()}日`
          }
        })
        const arr = [];
        for (let item of changeTimeOrder) {
          const index = arr.findIndex(n => n.createtime == item.createtime);
          if (index != -1) {
            arr[index].totalprice += item.totalprice
          } else {
            arr.push(item);
          }
        }
        shop['orderlist'] = arr

        // （3）获取所有管理员
        const getAdmin = new Promise((resolve, reject) => {
          db.query('select * from `admin` where shopid=?', shop.id, function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve(data);
            }
          })
        })
        const admins = await getAdmin
        const formatAdmins = admins.map(n => {
          let loginTime = new Date(n.loginTime);
          let FoomatTime = `${loginTime.getMonth() + 1}月${loginTime.getUTCDate()}日${loginTime.getHours() + 1}时`
          return {
            ...n,
            loginTime: FoomatTime
          }
        })
        shop['admins'] = formatAdmins
        res.send(shop);
      } else {
        throw Error("未查询到该商店")
      }
    }
  })
});

// 14.删除商店
router.get('/deleteShop', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  const { id } = req.query;
  db.query('delete from shop where id=?', [id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data);
    }
  })
});


// 15.商店加入新商品
router.post('/addNewFood', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { _id, shopid, imgUrl, name, price, fenlei, label } = req.body;
  db.query(`insert into foodlist (_id,shopid,icon,name,price,fenlei,label) 
  values (?,?,?,?,?,?,?)`,
    [_id, shopid, imgUrl, name, price, fenlei, JSON.stringify(label.map(n=>Number(n)))],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send(data);
      }
    })
})

// 16.删除商品
router.get('/deleteFoodData', async function (req, res, next) {
  console.log('---------删除了商品--------');
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  const { _id } = req.query;
  db.query('delete from foodlist where _id=?', [_id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data);
    }
  })
  console.log("会执行吗");
  db.query(`delete from shopcar where foodid=?`,
    [_id],
    function (err, data) {
      if (err) {
        // reject(err)
      } else {

      }
    })
});

// 17.修改商品
// { 
//   "_id": "1666147987130", 
//   "shopid": "1", 
//   "icon": "http://restaurant-imgs.oss-cn-wulanchabu.aliyuncs.com/1666148011553.png", 
//   "name": "布丁奶茶32332", 
//   "price": "123232", 
//   "fenlei": "热门推荐333", 
//   "label": [ 1, 2, 4, 3, 5, 6, 7 ] 
// }
router.get('/updataFoodListInfo', function (req, res, next) {
  const { _id, shopid, icon, name, price, fenlei, label } = req.query;
  db.query('update `foodlist` set icon=?,name=?,price=?,fenlei=?,label=? where _id=? and shopid=?',
    [icon, name, price, fenlei, JSON.stringify(label), _id, shopid],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({
          code: 200,
          data
        })
      }
    })
});
module.exports = router;